package logic

import (
	"api/appconfig"
	"api/pkg"
	"context"
	"strconv"
	"time"
	"user_srv/user"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginRequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	res, err := l.svcCtx.UserSrv.GetUserInfo(l.ctx, &user.GetUserInfoByUsernameRequest{Username: req.Username})
	if err != nil {
		return &types.Response{
			Code:    -1,
			Message: "服务器内部错误",
			Data:    nil,
		}, nil
	}
	if res.UserId == 0 {
		return &types.Response{
			Code:    -2,
			Message: "用户名不存在",
			Data:    nil,
		}, nil
	}
	//get := "123"
	//if pkg.Md5(req.Password+get) != req.Password {
	//	return &types.Response{
	//		Code:    -3,
	//		Message: "密码错误",
	//		Data:    nil,
	//	}, nil
	//}

	token, err := pkg.GetJwtToken(appconfig.AppConf.AccessSecret, time.Now().Unix(), int64(appconfig.AppConf.AccessExpire), strconv.FormatInt(res.UserId, 10))
	if err != nil {
		return &types.Response{
			Code:    -4,
			Message: "服务器内部错误",
			Data:    nil,
		}, nil
	}
	return &types.Response{
		Code:    0,
		Message: "登录成功",
		Data: map[string]interface{}{
			"token": token,
		},
	}, nil
}
